#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 21-3-10 下午2:18
# @Author  : zgd
# @Site    : 
# @File    : views.py
# @Software: PyCharm
from flask import g
from flask import jsonify
from flask import render_template
from flask import request
from flask import session

from info.models import User, News, Category
from info.utils.commons import user_login_data
from info.utils.response_code import RET
from . import index_blue
from flask import current_app



# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据
@index_blue.route('/newslist')
def newslist():
    """
    1. 获取参数
    2. 参数类型转换
    3. 分页查询
    4. 获取到分页对象中的属性,总页数,当前页,当前页的对象列表
    5. 将对象列表转成字典列表
    6. 携带数据,返回响应
    :return:
    """
    # 1. 获取参数
    cid = request.args.get("cid","1")
    page = request.args.get("page","1")
    per_page = request.args.get("per_page","10")

    # 2. 参数类型转换
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        page = 1
        per_page = 10

    # 3. 分页查询,传入页码，一页几条 cid传入分类id
    try:
        """
        #第一种
        #判断新闻分类是否为1
        if cid =="1":
            pagenate = News.query.filter().order_by(News.create_time.desc()).paginate(page,per_page,False)
        else:
            pagenate = News.query.filter(News.category_id == cid).order_by(News.create_time.desc()).paginate(page,
                                                                                                             per_page,
        """

        """
        第二种
        filters = ""
        if cid != "1":
            filters = (News.category_id == cid)

        pagenate = News.query.filter(filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
        """

        """
        第三种
        """
        filters = [News.status == 0]
        if cid != "1":
            filters.append(News.category_id == cid)

        # 继续添加更多的过滤条件 下面*.filters拆包后就添加上条件
        # filters.append(News.create_time<'2019-01-01')

        pagenate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR ,errmsg="获取新闻失败")


    # 4. 获取到分页对象中的属性,总页数,当前页,当前页的对象列表
    totalPage = pagenate.pages
    currengPage = pagenate.page
    items = pagenate.items

    # 5. 将对象列表转成字典列表
    news_list = []
    for news in items:
        news_list.append(news.to_dict())


    # 6. 携带数据,返回响应

    return jsonify(errno=RET.OK ,errmsg="获取新闻成功",totalPage=totalPage,currengPage=currengPage,newsList=news_list)





@index_blue.route("/",methods=["GET",'POST'])
@user_login_data
def show_index():

    #获取用户登陆信息
    user_id = session.get("user_id")
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
    # user_dic = {
    #     "nick_name":user.nick_name,
    #     "mobile" : user.mobile
    # }

    # 根据点击量查询热门新闻10条，拼接到ｄａｔａ中
    try:
        news = News.query.order_by(News.clicks.desc()).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR ,errmsg="获取新闻失败")

    #新闻对象列表转化为字典列表
    news_list = []
    for item in news:
        news_list.append(item.to_dict())


    # 查询所有的分类数据
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR ,errmsg="获取分类失败")

    categories_list = []
    for category  in categories:
        categories_list.append(category.to_dict())


    data = {
        "user_info":g.user.to_dict() if g.user else "",
        "news_list" : news_list,
        "categories_list":categories_list
    }

    return render_template('news/index.html',data=data)


# 处理网站接口,需要使用curreng_app.send_static_file('filename')
#send_static_file
@index_blue.route('/favicon.ico')
def get_web_logo():

    return current_app.send_static_file('news/favicon.ico')




# 统一返回４０４页面
@index_blue.route('/404')
@user_login_data
def page_not_found():

    data = {
        "user_info":g.user.to_dict() if g.user else ""
    }
    return render_template("news/404.html",data=data)





